import React, { useState, useRef, useEffect } from 'react';
import { useAlita } from 'redux-alita';
import style from './index.module.less';
import { uuid } from '../../utils/randomNumber';
import umbrella from 'umbrella-storage';
import { Input, Button, Icon, message } from 'antd';
import { getCurrentTime } from '../../utils/date';
import { getChartList, getSelectPcReceiveCount, updateStatus } from '../../api/chart';
import img1 from '../../style/imgs/logo.jpg';
import img3 from '../../style/imgs/user.png';
import img2 from '../../style/imgs/chart/mclose.png';

const { TextArea } = Input;

let wsObj = null;
let userId = umbrella.getLocalStorage('userId');
if (!userId) {
    userId = uuid();
    umbrella.setLocalStorage('userId', userId);
}
let reconnectNum = 1;
let timeout = null;
const Chart = () => {
    const [chartIsshow, setChartIsshow] = useAlita({ chartIsshow: true }, { light: true });
    // 组件挂载初始化以及卸载时关闭链接
    useEffect(() => {
        // 获取聊天记录
        getDataList();
        // 鼠标进入聊天框外面禁止页面滚动
        const chartBodyDom = document.querySelector('.chartBody');
        const chartBody = document.querySelector('.chartBody');
        chartBodyDom.addEventListener('mouseenter', () => {
            document.body.style.overflowY = 'hidden';
            document.body.style.paddingRight = '8px';
            chartBody.style.right = '7px';
        });
        chartBodyDom.addEventListener('mouseleave', () => {
            document.body.style.overflow = 'auto';
            document.body.style.paddingRight = '0px';
            chartBody.style.right = '0px';
        });
        return () => {
            // 组件卸载关闭链接
            if (wsObj) {
                wsObj.ws.close();
                reconnectNum = 1;
            }
            if (timeout) {
                clearInterval(timeout);
                timeout = null;
            }
        };
    }, []);
    // const [isShow, setIsShow] = useState(true);
    const [headerTitle, setHeaderTitle] = useState('连接中请稍后...');
    const [chartList, setChartList] = useState([
        // {
        //   id: 0,
        //   msg: `<p>您好！这里是万方寰宇论文编译，我是万方寰宇在线学术客服Tina，很高兴为您服务！请在下方留言您想咨询的服务：</p>
        //   <span style='color: rgb(0, 131, 230);
        //       font-size: 16px;'>1.论文润色</span>   <span style='color: rgb(0, 131, 230);
        //       font-size: 16px;'>2.学术翻译</span> <span style='color: rgb(0, 131, 230);
        //       font-size: 16px;'> 3.查重去重</span>
        //   <span style='color: rgb(0, 131, 230);
        //       font-size: 16px;'>4.协助投稿</span>   <span style='color: rgb(0, 131, 230);
        //       font-size: 16px;'>5.预审评估</span>  <span style='color: rgb(0, 131, 230);
        //       font-size: 16px;'>6.全程无忧发表服务</span>
        //       <h3>咨询电话：18033693009</h3>
        //   客服微信：131-2108-1606（预存款及了解相关优惠活动请添加客服微信）`,
        //   type: "robot",
        //   time: "2024-10-26 15:00:00",
        // }
    ]);
    // 为了在函数中获取到最新的值，需要使用useRef, usestate只能获取到上次的值，会慢一拍
    const chartListRef = useRef([]);

    useEffect(() => {
        chartListRef.current = chartList;
        setTimeout(() => {
            console.log(chartListRef.current.length, totalRef.current);
            // 滚动到顶部展示欢迎语
            if (
                chartListRef.current.length > 0 &&
                chartListRef.current[0].id !== 'welcome' &&
                chartListRef.current.length === totalRef.current - 1
            ) {
                // 到第一条数据了，展示欢迎语
                const newList = chartListRef.current;
                newList.unshift({
                    id: 'welcome',
                    msg: `<p>您好！这里是万方寰宇论文编译，我是万方寰宇在线学术客服Tina，很高兴为您服务！请在下方留言您想咨询的服务：</p>
          <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>1.论文润色</span>   <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>2.学术翻译</span> <span style='color: rgb(0, 131, 230);
              font-size: 16px;'> 3.查重去重</span>
          <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>4.一对一管家服务</span>   <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>5.全方位无忧文字指导</span>
              <h3>咨询电话：131-2108-1606</h3>
          客服微信：131-2108-1606`,
                    type: 'robot',
                    time: getCurrentTime(),
                });
                setChartList(() => [...newList]);
            } else if (chartListRef.current.length === 0) {
                const newList = chartListRef.current;
                newList.unshift({
                    id: 'welcome',
                    msg: `<p>您好！这里是万方寰宇论文编译，我是万方寰宇在线学术客服Tina，很高兴为您服务！请在下方留言您想咨询的服务：</p>
          <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>1.论文润色</span>   <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>2.学术翻译</span> <span style='color: rgb(0, 131, 230);
              font-size: 16px;'> 3.查重去重</span>
          <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>4.一对一管家服务</span>   <span style='color: rgb(0, 131, 230);
              font-size: 16px;'>5.全方位无忧文字指导</span>
              <h3>咨询电话：131-2108-1606</h3>
          客服微信：131-2108-1606`,
                    type: 'robot',
                    time: getCurrentTime(),
                });
                setChartList(() => [...newList]);
            } else if (chartListRef.current[0].id === 'welcome') {
                // const newList = chartListRef.current;
                // newList.splice(0, 1);
                // setChartList(() => [...newList]);
            }
        }, 500);
    }, [chartList]);

    const [msgInput, setMsgInput] = useState('');
    // 最小化聊天框
    let [msgNum, setMsgNum] = useState(0);
    function handleClose(boolean) {
        if (chartIsshow) {
            setChartIsshow('chartIsshow', boolean);
            // 开启轮询
            timeout = setInterval(() => {
                getMessage();
            }, 2000);
        } else {
            // 更新为已读
            updateStatus({
                type: 1,
                fromUserId: queryParamsRef.current.fromUserId,
                toUserId: umbrella.getLocalStorage('toUserId') || '',
            });
            // 停止轮询
            clearInterval(timeout);
            timeout = null;
            setChartIsshow('chartIsshow', boolean);
            requestAnimationFrame(() => {
                handleScroll();
            });
        }
    }
    // 获取新消息数量
    async function getMessage() {
        const res = await getSelectPcReceiveCount({
            fromUserId: userId,
            toUserId: umbrella.getLocalStorage('toUserId') || '',
        });
        setMsgNum(() => res.data);
    }
    // 输入事件
    function handleInput({ target: { value } }) {
        setMsgInput(() => value);
    }
    // 回车事件
    function handleKeyDown(e) {
        if (e.keyCode === 13) {
            handleEnter();
        }
    }
    // 发送消息
    function handleEnter() {
        if (msgInput.trim() === '') return;
        const time = getCurrentTime();
        const newList = [
            ...chartListRef.current,
            {
                id: chartListRef.current.length + 1,
                msg: msgInput,
                type: 'user',
                time,
            },
        ];
        setChartList(() => [...newList]);
        requestAnimationFrame(() => {
            handleSend(msgInput, time);
            setMsgInput('');
            handleScroll();
        });
    }

    //滚动到底部
    function handleScroll() {
        const chartContent = document.querySelector('.chartContent');
        chartContent.scrollTo({
            top: chartContent.scrollHeight,
            behavior: 'smooth', // 可选，平滑滚动效果
        });
    }

    /************************ 对话接口相关 start *************************************/
    class WsControl {
        constructor(path) {
            this.path = path;
            // 定义请求头
            this.ws = new WebSocket(path);
            this.ws.onopen = () => {
                console.log('连接成功');
                setHeaderTitle('连接成功请开始聊天');
                reconnectNum = 1;
            };
            this.ws.onmessage = function (data) {
                const dataObj = JSON.parse(data.data);
                if (dataObj.message.length === 0 && dataObj.toUserId.length !== 0) {
                    // 第一次发送消息，获取toUserId(随机的哪个客服)，之后的消息都对接这个客服
                    umbrella.setLocalStorage('toUserId', dataObj.toUserId);
                } else if (dataObj.message.length !== 0 && dataObj.type === 1) {
                    setChartList(() => [
                        ...chartListRef.current,
                        {
                            id: chartListRef.current.length + 1,
                            msg: dataObj.message,
                            type: 'robot',
                            time: dataObj.time,
                        },
                    ]);
                    requestAnimationFrame(() => {
                        handleScroll();
                    });
                }
            };
            this.ws.onclose = () => {
                console.log('链接关闭');
                setHeaderTitle('连接中请稍后...');
                if (reconnectNum < 10) {
                    setTimeout(() => {
                        reconnectNum += 1;
                        requestAnimationFrame(() => {
                            console.log('重新链接', reconnectNum);
                        });
                        handleLink();
                    }, 1000);
                } else {
                    console.log('链接失败');
                    setHeaderTitle('聊天窗口链接失败，请刷新重试！！！');
                    message.error('聊天窗口链接失败，请刷新重试！！！');
                }
            };
            this.ws.onerror = () => {
                console.log('链接错误');
            };
        }
        path;
        ws;
    }
    // 获取聊天记录
    // 获取列表页传参
    // interface queryParamsIn {
    //   type: number;
    //   fromUserId: string;
    //   pageNo: number;
    //   pageSize: number;
    // }
    let [queryParams, setQueryParams] = useState({
        type: 1,
        fromUserId: userId,
        pageNo: 1,
        pageSize: 6,
    });
    let queryParamsRef = useRef(queryParams);
    useEffect(() => {
        queryParamsRef.current = queryParams;
    }, [queryParams]);
    let [total, setTotal] = useState(0);
    const totalRef = useRef(0);
    useEffect(() => {
        totalRef.current = total;
    }, [total]);

    // 加载更多
    function handleMore() {
        setQueryParams(() => ({
            ...queryParams,
            pageNo: queryParamsRef.current.pageNo + 1,
        }));
        if (chartListRef.current[0].id === 'welcome') {
            const newList = [...chartListRef.current];
            newList.splice(0, 1);
            setChartList(() => [...newList]);
        }
        setTimeout(() => {
            getDataList(false);
        }, 0);
    }

    // 获取聊天记录
    async function getDataList(toBtm = true) {
        const params = {
            ...queryParamsRef.current,
            toUserId: umbrella.getLocalStorage('toUserId') || '',
        };
        const res = await getChartList(params);
        setTotal(res.data.total + 1);
        const list = res.data.list.map((item, index) => {
            return {
                id: chartListRef.current.length + index + 1,
                type: item.fromUserId === userId ? 'user' : 'robot',
                msg: item.message,
                time: item.createTime,
            };
        });
        setChartList(() => (chartListRef.current = [...list, ...chartListRef.current]));
        handleLink();
        requestAnimationFrame(() => {
            if (toBtm) {
                handleScroll();
            }
        });
    }

    function handleLink() {
        let wsPath = '';
        if (process.env.NODE_ENV === 'development') {
            // wsPath = "ws://192.168.1.137:8901/imserver/";
            wsPath = 'wss://www.wfhyedit.com/imserver/';
        } else {
            wsPath = 'wss://www.wfhyedit.com/imserver/';
        }
        wsObj = new WsControl(wsPath + userId);
        // wsObj = new WsControl("ws://192.168.1.137:8901/imserver/" + userId);
    }
    function handleSend(msgInput, time) {
        wsObj.ws.send(
            JSON.stringify({
                type: 1,
                fromUserId: userId,
                toUserId: umbrella.getLocalStorage('toUserId') || '',
                message: msgInput,
                time,
            })
        );
    }

    // 判断是否展示加载更多
    const [showMore, setShowMore] = useState(false);
    // function setMoreDom() {
    //   // if (chartListRef.current.length > 0) {
    //   //   if (chartListRef.current[0].id === "welcome") {
    //   //     if (totalRef.current > (chartListRef.current.length + 1)) {
    //   //       alert(1)
    //   //       str = <div className={style.chart_more} onClick={handleMore}>加载更多</div>;
    //   //     }
    //   //   } else {
    //   //     if (totalRef.current > chartListRef.current.length) {
    //   //       alert(2)
    //   //       str = <div className={style.chart_more} onClick={handleMore}>加载更多</div>;
    //   //     }
    //   //   }
    //   // } else {
    //   //   setShowMore(false);
    //   // }
    //   if (chartListRef.current[0].id === "welcome" && totalRef.current > (chartListRef.current.length - 1)) {

    //   }
    // }
    /************************ 对话接口相关 end *************************************/
    return (
        <>
            <div
                className={`${style.chart_thumbnail} ${chartIsshow ? style.hide : ''}`}
                onClick={() => handleClose(true)}
            >
                {msgNum > 0 && <span className={style.msg_num}>{msgNum}</span>}
                {msgNum === 0 && <img src={img2} alt="图片加载失败" className={style.msg_icon} />}
            </div>
            <div className={`${style.chart_body} ${!chartIsshow ? style.hide : ''} chartBody`}>
                <div className={style.chart_header}>
                    <div className={style.header_left}>
                        <img src={img1} alt="图片加载失败" />
                        <div className={style.header_title}>
                            <span>{headerTitle}</span>
                        </div>
                    </div>
                    <div className={style.header_right}>
                        <div className={style.tool_body} onClick={() => handleClose(false)}>
                            <span />
                        </div>
                    </div>
                </div>
                <div className={`${style.chart_content} ${style.clearfix} chartContent`}>
                    {total > chartList.length && (
                        <div className={style.chart_more} onClick={handleMore}>
                            加载更多
                        </div>
                    )}
                    {chartList.map((item) => {
                        let dom;
                        if (item.type === 'robot') {
                            dom = (
                                <div className={style.robot_msg} key={item.id}>
                                    <img src={img1} alt="图片加载失败" />
                                    <div className={style.msg_content}>
                                        <div className={style.msg_time}>{item.time}</div>
                                        <p dangerouslySetInnerHTML={{ __html: item.msg }} />
                                    </div>
                                </div>
                            );
                        } else if (item.type === 'user') {
                            dom = (
                                <div className={style.user_msg} key={item.id}>
                                    <div className={style.msg_content}>
                                        <div className={style.msg_time}>{item.time}</div>
                                        <p dangerouslySetInnerHTML={{ __html: item.msg }} />
                                    </div>
                                    <img src={img3} alt="图片加载失败" />
                                </div>
                            );
                        }
                        return dom;
                    })}
                </div>
                <div className={style.chart_footer}>
                    <div className={style.footer_title} />
                    <TextArea
                        value={msgInput}
                        onChange={handleInput}
                        placeholder="请在此输入文本"
                        autoSize={{ minRows: 4, maxRows: 4 }}
                        onKeyDown={handleKeyDown}
                    />
                    <div className={style.send_body}>
                        <Button type="primary" onClick={handleEnter}>
                            发送
                        </Button>
                    </div>
                </div>
            </div>
        </>
    );
};

export default Chart;
